package org.ezplatform.office.meeting.info.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.ezplatform.core.dao.jpa.JpaBaseDao;
import org.ezplatform.core.service.BaseService;
import org.ezplatform.office.meeting.info.dao.SignedAddressDao;
import org.ezplatform.office.meeting.info.entity.SignedAddress;
import org.ezplatform.util.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class SignedAddressService extends BaseService<SignedAddress, String>{
    
    @Autowired
    private SignedAddressDao signedAddressDao;
    
    @Override
    protected JpaBaseDao<SignedAddress, String> getEntityDao() {
        return signedAddressDao;
    }
    
    /**
     * 保存会议签到的签到地址
     * @param applyRecordId
     * @param json
     */
    public void saveSignedAddress(String applyRecordId, String json){
    	List<Map<String, String>> addrList = JsonUtils.readListValue(json);
    	if(addrList!=null && !"".equals(applyRecordId)){
    		this.signedAddressDao.delByRecordId(applyRecordId);
    		for(int i=0; i<addrList.size(); i++){
    			Map<String, String> map = addrList.get(i);
    			String longitude = map.get("lng");
    			String latitude = map.get("lat");
    			SignedAddress address = new SignedAddress();
				address.setApplyRecordId(applyRecordId);
				address.setLongitude(longitude);
				address.setLatitude(latitude);
				address.setSignedAddress(map.get("address"));
				this.signedAddressDao.save(address);
        	}
    	}
    }
    
    /**
     * 根据会议id查找会议签到地址
     * @param applyRecordId
     * @return
     */
    public List<SignedAddress> findByRecordId(String applyRecordId){
    	return this.signedAddressDao.findByApplyRecordId(applyRecordId);
    }

	/**
	 * 根据外间fkid查找会议签到地址
	 * @param fkid
	 * @return
	 */
	public List<SignedAddress> findByFkid(String fkid){
		return this.signedAddressDao.findByFkidId(fkid);
	}
    
    /**
     * 根据会议id查找会议签到地址
     * @param applyRecordId
     * @return
     */
    public List<Map<String, String>> findByARecordId(String applyRecordId){
    	List<Map<String, String>> result = new ArrayList<>();
    	List<SignedAddress> list = this.signedAddressDao.findByApplyRecordId(applyRecordId);
    	for (SignedAddress address : list) {
    		if(address != null){
    			Map<String, String> map = new HashMap<>();
    			map.put("lng", address.getLongitude());
    			map.put("lat", address.getLatitude());
    			map.put("address", address.getSignedAddress());
    			result.add(map);
    		}
		}
    	return result;
    }
    
    public int deleteSignAddress(String... recordId){
    	return this.signedAddressDao.delByRecordId(recordId);
    }
}